package com.uniview.plugins.adapter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.uniview.entity.po.Employees;
import com.uniview.entity.po.UserRole;
import com.uniview.service.EmployeesService;
import com.uniview.service.RoleService;
import com.uniview.util.SpellHelper;

/**
 * 员工同步线程
 * 
 * @author ideapad
 *
 */
@Service("employessHelper")
public class EmployeesHelper {

	private Logger logger = Logger.getLogger(EmployeesHelper.class);

	@Autowired
	private Ad_EmployeesService ad_EmployeesService;

	@Autowired
	private EmployeesService employeesService; // 内部库接口

	@Autowired
	private RoleService roleService;


	@Value("#{configProperties['uniview.pageSize']}")
	private Integer pageSize;

	@Value("#{configProperties['uniview.interval']}")
	private Integer interval;

	@Value("#{configProperties['uniview.roleId']}")
	private Integer roleId;

	@Value("#{configProperties['uniview.synDept']}")
	private String synDept;
	
	/**
	 * 同步员工数据
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public synchronized void syncEmployees() {
		try {
			// 查询本地数据是否存在
			Integer totalRows = ad_EmployeesService.getTotalRows();
			Long localCounts = employeesService.getTotalRows();
			if (localCounts != null && localCounts > 0 
					&& totalRows != null && totalRows > 0) {
				// 表示存在数据
				boolean result = employeesService.deleteAll();
				if (result) {
					insetEmployees();
				}
			} else {
				insetEmployees();
			}
		} catch (Exception e) {
			logger.error("同步员工数据异常", e);
		}
	}

	private void insetEmployees() {
		// 计算页数
		Integer totalRows = ad_EmployeesService.getTotalRows();
		int totalPage = (int)((totalRows + pageSize -1) / pageSize); 
		List<Employees> tempEmy = new ArrayList<Employees>();
		String[] orgs = synDept.split(";");
		for (int i = 1; i <= totalPage; i++) {
			List<Employees> listEmy = ad_EmployeesService.findEmployeesByPage(pageSize, i);
			tempEmy.clear();
			
			for (Employees emy : listEmy) {
				boolean isContains = false;
				for(String tempStr : orgs) {
					if((StringUtils.isNotBlank(emy.getOrgName()) && emy.getOrgName().contains(tempStr)) 
							|| "y02685".equalsIgnoreCase(emy.getEmpCode())){
						isContains = true;
						break;
					}
				}
				
				//需要同步的用户
				if(isContains){
					// 插入拼音操作
					emy.setPinyin(SpellHelper.getEname(emy.getEmpName()));
					emy.setEmType(0); //从K3同步的用户设置为内部用户
					emy.setWorkType("内部员工");
					UserRole ur = roleService.findRecouseRoleByWorkNo(emy.getEmpCode(), roleId);
					if(ur == null){
						//插入默认角色
						ur = new UserRole();
						ur.setCreateDate(new Date());
						ur.setRoleId(roleId);
						ur.setUserId(emy.getEmpCode());
						ur.setDeptName(emy.getOrgName());
						ur.setUserName(emy.getEmpName());
						ur.setPhone(emy.getPhone());
						roleService.addUserRole(ur);
					}
					
					tempEmy.add(emy);
				}
			}
			if (tempEmy != null && tempEmy.size() > 0) {
				employeesService.saveEmployeesBySql(tempEmy, pageSize);
			}
		}
	}

	// 同步更新员工信息任务
	public void syncUpdateEmployees() {
		Map<String, String> timeZone = getTimeZones(new Date());
		List<Employees> list = ad_EmployeesService.findEmployeesByTime(timeZone.get("beginDate"),
				timeZone.get("endDate"));
		if (null != list && list.size() > 0) {
			for (Employees emy : list) {
				emy.setPinyin(SpellHelper.getEname(emy.getEmpName()));
			}
			employeesService.SaveOrUpdateEmployees(list);
		}
	}

	private Map<String, String> getTimeZones(Date date) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
//		calendar.set(Calendar.DAY_OF_MONTH, -1);
		calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - interval);
		String endDate = df.format(date);
		String beginDate = df.format(calendar.getTime());
		Map<String, String> map = new HashMap<String, String>();
		map.put("beginDate", beginDate);
		map.put("endDate", endDate);
		return map;
	}
}
